//
//  PromotionSettingViewController.m
//  rrbi
//
//  Created by mac book on 2018/12/4.
//

#import "PromotionSettingViewController.h"
#import "PromotionTableViewCell.h"
#import "CustomAlertView.h"

#define HeaderView_Height  50/HEIGHT_6S_SCALE


@interface PromotionSettingViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong) NetPage* page;
@property(nonatomic,strong) UIButton* changeBtn;
@property(nonatomic,strong) UILabel* moneyLabel;


@end

@implementation PromotionSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationItem.title =  @"促销设置";
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(rightButton)];
    
    [self creatSubViews];
    
    [self refreshDataSource];

    
}
-(void)rightButton{
    
    CustomAlertView *alertView = [[CustomAlertView alloc] initAlert];
    //            __weak typeof(alertView) weakAlert = alertView;
    alertView.resultIndex = ^(NSString *fullPrice, NSString *cutPrice) {
        
        NSLog(@"fullPrice = %@",fullPrice);
        NSLog(@"cutPrice = %@",cutPrice);
        NSDictionary* arg = @{@"ince":@"add_shop_promotion_new",
                              @"sid":[UserModel sharedInstanced].ru_Id,
                              @"man":fullPrice,
                              @"jian":cutPrice
                              };
        [NetRepositories addPromotion:arg complete:^(EnumNetResponse react, id obj, NSString *message) {
            
            ShowMessage(@"添加成功");
            self.page.pageIndex = 1;
            [self queryData];
        }];
        
        
        

    };
    [alertView showAlertView];
    
}

-(void)creatSubViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) -NAVGATIONBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.tableHeaderView = [self creatHeaderView];

    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
}

-(UIView *)creatHeaderView{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HeaderView_Height)];
    //self.headerView.backgroundColor = [UIColor whiteColor];
    
    self.changeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.changeBtn addTarget:self action:@selector(changeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.changeBtn.layer.masksToBounds = YES;
    self.changeBtn.layer.cornerRadius = 5;
    self.changeBtn.titleLabel.font= kFontNameSize(14);
    [headerView addSubview:self.changeBtn];
    [self.changeBtn setTitle:@"修改" forState:UIControlStateNormal];
    self.changeBtn.backgroundColor=  getColor(greenBackColor);
    [self.changeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(50);
        make.right.equalTo(headerView).mas_offset(-20);
        make.centerY.equalTo(headerView);
    }];
    
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor grayColor];
    [headerView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.right.equalTo(headerView);
        make.bottom.equalTo(headerView);
    }];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"新用户减免：";
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = kFontNameSize(14);
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(100);
        make.left.equalTo(headerView).mas_offset(20);
        make.centerY.equalTo(headerView);
    }];
    
    
    self.moneyLabel = [[UILabel alloc]init];
    self.moneyLabel.textColor = [UIColor grayColor];
    self.moneyLabel.font = kFontNameSize(14);
    self.moneyLabel.layer.borderWidth = 0.5;
    self.moneyLabel.layer.cornerRadius = 5;
    self.moneyLabel.textAlignment = NSTextAlignmentCenter;
    self.moneyLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [headerView addSubview:self.moneyLabel];
    [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(90);
        make.left.equalTo(titleLabel.mas_right);
        make.centerY.equalTo(headerView);
    }];
    
    UILabel *yuanLabel = [[UILabel alloc]init];
    yuanLabel.text = @"元";
    yuanLabel.textColor = [UIColor grayColor];
    yuanLabel.font = kFontNameSize(14);
    [headerView addSubview:yuanLabel];
    [yuanLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.right.equalTo(self.changeBtn.mas_left);
        make.left.equalTo(self.moneyLabel.mas_right).mas_offset(5);
        make.centerY.equalTo(headerView);
    }];
    
    return headerView;
    
}

-(void)changeBtnAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"修改金额" preferredStyle:UIAlertControllerStyleAlert];
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入金额";
        textField.delegate = self;
//        textField.keyboardType = UIKeyboardTypeNumberPad;

    }];
    //增加取消按钮；
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        UITextField *inputInfo = alertController.textFields.firstObject;
        if (inputInfo.text.length == 0) {
            ShowMessage(@"修改金额不能为空!");
            return ;
        }else{
            NSDictionary* arg = @{@"ince":@"set_shop_promotion",
                                  @"sid":[UserModel sharedInstanced].ru_Id,
                                  @"new_user_sale":inputInfo.text
                                  };
            [NetRepositories changePromotion:arg complete:^(EnumNetResponse react, id obj, NSString *message) {
                
                ShowMessage(message);
                self.moneyLabel.text = inputInfo.text;
//                self.page.pageIndex = 1;
//                [self queryData];
            }];
            
            
        }
        
    }];
    
    
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:true completion:nil];
    
    
}

#pragma mark =====================================================  Data Source
-(void)queryData{
    
    NSDictionary* arg = @{@"ince":@"get_promotion_list",@"sid":[UserModel sharedInstanced].ru_Id, @"page":[WMHelper integerConvertToString:self.page.pageIndex]};
    [NetRepositories queryPromotion:arg page:self.page complete:^(EnumNetResponse react, NSArray *list, NSString *message, NSDictionary *mainDict) {
        if(self.page.pageIndex == 1){
            [self.dataArray removeAllObjects];
        }
        if(react == NetResponseSuccess){
            self.moneyLabel.text = [NSString stringWithFormat:@"%@",message];
            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.dataArray addObject:obj];
            }];
        }else if(react == NetResponseException){
            [self alertHUD:message];
        }else{
            [self alertHUD:message];
        }
        
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    }];
    
}
-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf queryData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];
    [self.tableView.mj_header beginRefreshing];
}




#pragma mark - ******* tableview代理方法 *******
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *cellID = @"CELL_ID";
    
    PromotionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if(!cell){
        cell = [[PromotionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MStore *model = self.dataArray[indexPath.row];
    cell.entity = model;
    cell.promotionDeleteBtnBlock = ^{
        NSDictionary* arg = @{@"ince":@"delete_manjian",
//                              @"sid":[UserModel sharedInstanced].ru_Id,
                              @"id":model.stroe_id
                              };
        NSLog(@"=====%@",arg);
        [NetRepositories deletePromotion:arg complete:^(EnumNetResponse react, id obj, NSString *message) {
            
            ShowMessage(message);
            self.page.pageIndex = 1;
            [self queryData];
        }];
        
    };
    return cell;
    
    
    
    
}
//限制输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (string.length != 0 ){
        //限制输入
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
        NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if (!basicTest) {
            return NO;
        }else{
            return YES;
        }
        
    }
    return YES;
}


-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(NetPage *)page{
    if(!_page){
        _page = [[NetPage alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
